import db, {aiConversion} from '../../database/lowDB/connectDb.js';
import {unioformDateTransform,autoIncreamentKey} from '../../utils/index.js'

class aiConversionModel {
    constructor() {
        this.tableName = 'aiConversion';
    }
   
    // 查询用户对应角色下的对话信息
    async getConversationByUserAndRole({userId, roleCode}) {
        const conversations = aiConversion.filter(conversation => 
            conversation.userId === userId && conversation.roleCode === roleCode
        );
        return conversations?.map(item=>{
            return {
                sessionId:item.sessionId,
                sessionContent:item.sessionContent,
                time:item.time,
            }
        })
    }

    // 新增对话信息
    async addConversation(conversationData) {
        const newConversation = {
            id: autoIncreamentKey(aiConversion),
            userId: conversationData.userId,
            roleCode: conversationData.roleCode,
            sessionId: conversationData.sessionId,
            sessionContent: conversationData.sessionContent,
            time: unioformDateTransform(new Date())
        };
        aiConversion.unshift(newConversation);
        db.write();
        return true;
    }

    // 删除用户对应角色下的对话信息
    async deleteConversationByUserAndRole({userId, roleCode}) {
        const initialLength = aiConversion.length;
        aiConversion.forEach((element,index) => {
            if( element.userId === userId  && element.roleCode === roleCode ){
                aiConversion.splice(index,1)
            }
        })
        db.write();
        return aiConversion.length < initialLength;
    }   
}   

export default new aiConversionModel();